package com.yuanhe.yunoj.judge.codeSandbox.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yuanhe.yunoj.common.ErrorCode;
import com.yuanhe.yunoj.exception.BusinessException;
import com.yuanhe.yunoj.judge.codeSandbox.CodeSandbox;
import com.yuanhe.yunoj.judge.codeSandbox.model.ExecuteCodeRequest;
import com.yuanhe.yunoj.judge.codeSandbox.model.ExecuteCodeResponse;
import org.apache.http.client.utils.HttpClientUtils;

/**
 * 远程代码沙箱
 */
public class RemoteCodeSandbox implements CodeSandbox {
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String SECRET_KEY = "secret";
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String url = "http://localhost:8090/executeCode";
        String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
        //发送HTTP请求
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, SECRET_KEY)
                .body(jsonStr)
                .execute()
                .body();
        if (StringUtils.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteSandbox error, message = " + responseStr);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);

    }
}
